package com.hellprototypes.hellwatch.assistant;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class IR_RemoteControl extends Activity {
    private final static String TAG = "HellWatch-IR_RemoteCtrl";
    private final static String TV_ChannelListFileName = "TV_ChannelList.txt";

    public IR_CtrlReceiver mIR_CtrlReceiver;

    public ListView mListViewCtrl;
    public ListView mListViewChannel;
    public TextView mTextViewTVListFile;
    public TextView mTextViewIRmsg;

    private String[] mListCtrlStr = {
            "Power OFF1","Power OFF2","Volume+","Volume-",
            "Menu","OK","Exit","Back","Channel+","Channel-","Mute",
    };
    private int[] mListCtrlKeyMap = {
            0x17,0x18,0x1A,0x19,0x14,0x16,0x13,0x10,0x12,0x11,0x15,
    };
    private ArrayList<String> mListChannelStr;
    public Map<Integer,byte[]> mKey_IR_Code_Map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ir_remote_control);

        mListViewCtrl = (ListView)findViewById(R.id.lv_control);
        mListViewChannel= (ListView)findViewById(R.id.lv_channels);
        mTextViewTVListFile = (TextView)findViewById(R.id.tv_IR_Code_File);
        mTextViewIRmsg = (TextView)findViewById(R.id.tv_send_ir_code);

        mListChannelStr = new ArrayList<String>();
        mKey_IR_Code_Map= new HashMap<Integer,byte[]>();

        try {
            load_tv_channel_list();
        } catch (IOException e) {
            e.printStackTrace();
        }
        build_ir_ctrl_ui();


        SharedPreferences preferences=getSharedPreferences("HellWatchIRCtrl", Context.MODE_PRIVATE);
        String fileName=preferences.getString("IR_KeyIdxFileName", "");
        if(!fileName.isEmpty()) {
            try {
                loadIrCodeFromFile(fileName);
                mTextViewTVListFile.setText("红外编码：" + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Log.d(TAG, "# onCreate()" + fileName);
    }

    @Override
    public void onStart() {
        mIR_CtrlReceiver = new IR_CtrlReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Common.HWIR_ACTION);
        registerReceiver(mIR_CtrlReceiver, filter);

        Log.d(TAG, "# onStart()");
        super.onStart();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "# onStop()");
        unregisterReceiver(mIR_CtrlReceiver);
        super.onStop();
    }

    public void build_ir_ctrl_ui() {
        mListViewCtrl.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mListCtrlStr));
        mListViewCtrl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position,long id) {
                //Toast.makeText(getApplicationContext(),"您选择了" + mListCtrlStr[position], Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Common.HWIR_ACTION);
                intent.putExtra(Common.BUNDLE_KEY_IR_CTRL_IDX, mListCtrlKeyMap[position]);
                sendBroadcast(intent);
            }
        });

        mListViewChannel.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mListChannelStr));
        mListViewChannel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                //Toast.makeText(getApplicationContext(),"您选择了" + mListChannelStr[position], Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Common.HWIR_ACTION);
                intent.putExtra(Common.BUNDLE_KEY_IR_CH_NAME, mListChannelStr.get(position));
                sendBroadcast(intent);
            }
        });
    }

    public void loadIrCodeFromFile(String fileName) throws IOException {
        String filePath = Environment.getExternalStorageDirectory().toString() + "/HellWatch/" + fileName;
        File file = new File(filePath);
        if(!file.exists()) {
            Toast.makeText(getApplicationContext(),"文件不存在:" + filePath, Toast.LENGTH_LONG).show();
            return;
        }
        InputStream is = new FileInputStream(file);
        long length = file.length();

        if (length < 7) {
            is.close();
            return;
        }
        byte[] IrDataBytes = new byte[(int)length];
        int offset = 0;
        int numRead;
        while (offset < IrDataBytes.length && (numRead=is.read(IrDataBytes, offset, IrDataBytes.length-offset)) >= 0) {
            offset += numRead;
        }
        is.close();

        Log.d(TAG, "# Load File Data = " + Common.byte2hex(IrDataBytes));
        //=================================
        mKey_IR_Code_Map.clear();
        int index =0;
        while(index < IrDataBytes.length) {
            byte [] byte6 = new byte[6];
            int KEY_index = (int)IrDataBytes[index++];
            for(int i=0; i<6; i++) {
                byte6[i] = IrDataBytes[index++];
            }
            mKey_IR_Code_Map.put(KEY_index, byte6);
        }
    }

    public void on_tv_IR_code_file_click(View view) {
        disp_load_IR_code_file_list();
    }

    public void disp_load_IR_code_file_list() {
        String path = Environment.getExternalStorageDirectory().toString() + "/HellWatch";
        File dir = new File(path);
        File file[] = dir.listFiles();
        int items = file.length;
        if(items == 0) {
            Toast.makeText(getApplicationContext(),"没有找到文件", Toast.LENGTH_SHORT).show();
            return;
        }
        List<String> tv_fileName_list = new ArrayList<String>();
        for (int i=0; i < items; i++) {
            String fileName = file[i].getName();
            if((fileName.length() > 3) && fileName.endsWith(".ir")) {
                tv_fileName_list.add(fileName);
            }
        }
        if(tv_fileName_list.size() == 0) {
            Toast.makeText(getApplicationContext(),"没有找到红外数据文件", Toast.LENGTH_SHORT).show();
            return;
        }
        //final  String [] IR_FileList = new String[ir_fileName_list.size()];
        final String[] TV_FileList = tv_fileName_list.toArray(new String[tv_fileName_list.size()]);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择一个文件");
        builder.setItems(TV_FileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), TV_FileList[item], Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Common.HWIR_ACTION);
                intent.putExtra(Common.BUNDLE_KEY_IR_TLOAD, TV_FileList[item]);
                sendBroadcast(intent);
            }
        });
        builder.create().show();
    }

    public boolean load_tv_channel_list() throws IOException {
        String filePath = Environment.getExternalStorageDirectory().toString() + "/HellWatch";
        File dir = new File(filePath);
        filePath += "/" + TV_ChannelListFileName;
        if (!dir.exists()){
            if (!dir.mkdir()){
                Toast.makeText(getApplicationContext(),"无法创建目录", Toast.LENGTH_SHORT).show();
                return false;
            }
            mListChannelStr = (ArrayList<String>) Arrays.asList(Common.FZ_TV_CH_List);
            write_default_tv_channel(filePath);
            return true;
        }
        File f = new File(filePath);
        if(f.exists()) {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                if((line.length() > 4) && (line.charAt(3) == ' ')) {
                    try{
                        int ch_num = Integer.parseInt(line.substring(0,3));
                        //Log.d(TAG, "ch_num = " + ch_num) ;
                        mListChannelStr.add(line);
                    }catch(NumberFormatException e){
                        Toast.makeText(getApplicationContext(),"频道格式不正确： " + line, Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "频道格式不正确： " + line + ", " + e) ;
                    }
                }
            }
            reader.close();
        } else {
            mListChannelStr = (ArrayList<String>) Arrays.asList(Common.FZ_TV_CH_List);
            write_default_tv_channel(filePath);
        }
        return true;
    }

    public void write_default_tv_channel(String fileName) throws IOException {
        FileWriter fw = new FileWriter(fileName);
        for (String lineStr : mListChannelStr) {
            fw.write(lineStr + "\r\n");
        }
        fw.close();
    }
    public void sendIRCodeToBLE(byte [] ir_code) {
        byte [] send_code = new byte[ir_code.length+1];
        send_code[0] = 0x02;//0x02: is for IR ctrl index code
        System.arraycopy(ir_code, 0, send_code, 1, ir_code.length);
        //Log.d(TAG, "# Send IR Code: " + Common.byte2hex(ir_code));
        mTextViewIRmsg.setText("IR:" + Common.byte2hex(ir_code).substring(3,9));

        Intent serviceIntent = new Intent(this, AssistantService.class);
        Bundle bundle = new Bundle();
        bundle.putByteArray(Common.BUNDLE_KEY_IR_SEND, send_code);
        serviceIntent.putExtras(bundle);
        startService(serviceIntent);
    }

    public void sendChannelNumber(int ch_num) {
        if(ch_num > 999) {
            return;
        }
        int hundreds = ch_num/100;
        int decade = (ch_num%100)/10;
        int single = ch_num%10;
        //Log.d(TAG, "sendChannelNumber:" + ch_num + "=" + hundreds + decade + single);

        byte [] ir_code;// = new byte[6];

        if((hundreds > 0) && mKey_IR_Code_Map.containsKey(hundreds)) {
            ir_code = mKey_IR_Code_Map.get(hundreds);
            sendIRCodeToBLE(ir_code);
            Log.d(TAG, "ir_code hundreds:" + hundreds + " # " + Common.byte2hex(ir_code));
        }
        if(((hundreds > 0) || (decade > 0)) && mKey_IR_Code_Map.containsKey(decade)) {
            ir_code = mKey_IR_Code_Map.get(decade);
            sendIRCodeToBLE(ir_code);
            Log.d(TAG, "ir_code decade:" + decade + " # " + Common.byte2hex(ir_code));
        }
        if(mKey_IR_Code_Map.containsKey(single)) {
            ir_code = mKey_IR_Code_Map.get(single);
            //Log.d(TAG, "ir_code 1:" + Common.byte2hex(ir_code));
            sendIRCodeToBLE(ir_code);
            Log.d(TAG, "ir_code single:" + single + " # " + Common.byte2hex(ir_code));
        } else {
            Toast.makeText(getApplicationContext(),"未找到按键码：" + single, Toast.LENGTH_SHORT).show();
        }
    }

    public class IR_CtrlReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Log.d(TAG, "# IR_LearnReceiver onReceive");
            String action = intent.getAction();
            if(action.equals(Common.HWIR_ACTION)) {
                Bundle bundle = intent.getExtras();
                if(bundle.containsKey(Common.BUNDLE_KEY_IR_CTRL_IDX)) {
                    Integer key_index = bundle.getInt(Common.BUNDLE_KEY_IR_CTRL_IDX);
                    byte [] ir_code;// = new byte[6];
                    if(mKey_IR_Code_Map.containsKey(key_index)) {
                        ir_code = mKey_IR_Code_Map.get(key_index);
                        sendIRCodeToBLE(ir_code);
                    } else {
                        Toast.makeText(getApplicationContext(),"没有找到键值：" + key_index, Toast.LENGTH_SHORT).show();
                    }
                } else
                if(bundle.containsKey(Common.BUNDLE_KEY_IR_CH_NAME)) {
                    String ch_name = bundle.getString(Common.BUNDLE_KEY_IR_CH_NAME);
                    int ch_num = Integer.parseInt(ch_name.substring(0,3));
                    sendChannelNumber(ch_num);
                } else
                if(bundle.containsKey(Common.BUNDLE_KEY_IR_TLOAD)) {
                    String fileName = bundle.getString(Common.BUNDLE_KEY_IR_TLOAD);
                    if(!fileName.isEmpty()) {
                        try {
                            loadIrCodeFromFile(fileName);
                            mTextViewTVListFile.setText("编码文件:" + fileName);
                            getSharedPreferences("HellWatchIRCtrl", Context.MODE_PRIVATE).edit().putString("IR_KeyIdxFileName", fileName);
                            SharedPreferences.Editor editor=getSharedPreferences("HellWatchIRCtrl",Context.MODE_PRIVATE).edit();
                            editor.putString("IR_KeyIdxFileName", fileName);
                            editor.commit();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.ir_remote_control, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_learning) {
            Intent intent = new Intent(this, IR_RemoteLearning.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_load_IR_code) {
            disp_load_IR_code_file_list();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
